<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>task1</title>
	<style>
		*{
			box-sizing: border-box;
		}
		body{
			font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
			font-size: 16px;
			background-color: #000;
		}
		#checkForm{
			width: 500px;
			height: 200px;
			background-color: #fff;
			margin: 200px auto;
			display: flex;
			align-items: center;
			border-radius: 5px;
			font-size: 1.2em;
		}
		#main{
			margin: 0 auto;
		}
		#main label{
			font-size: 1.2em;
		}
		#txt{
			border-radius: 5px;
			border: 2px solid lightgray;
			margin: 0 20px;
			width: 15em;
			height: 2em;
			font-size: 1em;
		}
		#main button{
			cursor: pointer;
			background-color: #2335FC;
			border: 2px solid #2335FC;
			width: 80px;
			border-radius: 5px;
			font-size: 1.2em;
			color:#fff;
		}
		button:hover{
			border-color: #4387F5; 
		}
		#prompt{
			display: block;
			margin-left: 75px;
			color: gray;
		}
	</style>
</head>
<body>
	<form id="checkForm" onkeydown="if(event.keyCode==13)return false;">
		<div id="main">
			<label for="txt">名称</label>
			<input type="text" id="txt" name="txt" required>
			<button id="check" type="button">验证</button>
			<span id="prompt">必填，长度为4~16个字符</span>
		</div>
	</form>
	<script>
		//模仿块级作用域，匿名函数立即执行
		(function(){
			var txt = document.getElementById('txt');
			var check = document.getElementById('check');
			var prompt = document.getElementById('prompt');

			//点击验证按钮，对输入框内容进行校验
			check.onclick = function(){
				var content = txt.value.trim();
				var len = 0;
				//输入字符串长度计算（英文及符号长度为1，中文及符号长度为2）
				for (var i = 0; i < content.length; i++) {
					if((/[^\x00-\xff]/).test(content[i])){
						len +=2;
					}else{
						len++;
					}
				}
				//输入框校验
				if(content == ''){
					txt.style.border = "1px solid red";
					prompt.innerHTML = "名称不能为空！";
					prompt.style.color = "red"; 
				}else if(!(len>=4 && len<=16)){
					txt.style.border = "1px solid red";
					prompt.innerHTML = "请输入4~16位字符！";
					prompt.style.color = "red"; 
				}else{
					txt.style.border = "1px solid green";
					prompt.innerHTML = "名称格式正确！";
					prompt.style.color = "green"; 
				}
			}

			//当输入框获取焦点时，恢复默认状态
			txt.onfocus = function(){
				txt.style.border = "1px solid lightgray";
				prompt.innerHTML = "必填，长度为4~16个字符";
				prompt.style.color = "gray"; 
			}
		})()
	</script>
</body>
</html>